package com.zb;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zb.eneity.Server;
import com.zb.mapper.ServerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

/**
 * 项目启动时初始化数据源
 */
@Component
@Order(Integer.MIN_VALUE)
public class InitTenantDataSource {

    @Autowired
    private ServerMapper serverMapper;

    @Autowired
    private DataSource dataSource;

    @Scheduled(
            cron = "${0 0/2 * * * ?}"
    )
    @PostConstruct
    private void initDataSource() {
        List<Server> servers = serverMapper.selectList(null);
        for (Server server : servers) {
            DataSource hikariDataSource = this.getHikariDataSource(server);
            ((TenantDynamicDataSource) dataSource).addDataSource(server.getDbName(), hikariDataSource);
        }
    }


    private DataSource getHikariDataSource(Server server) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(server.getUrl());
        config.setUsername(server.getUsername());
        config.setPassword(server.getPassword());
        config.setDriverClassName(server.getDriverClass());
        config.setConnectionTestQuery("SELECT 1");
        config.setPoolName("hikari-poolName-" + server.getDbName());
        return new HikariDataSource(config);
    }
}
